# -*- coding: utf-8 -*-
"""
Created on Mon Dec  1 15:18:44 2014

@author: wei
"""
from app import app
from flask import g,flash,session
from flask.ext.wtf import Form,RecaptchaField
from wtforms.form import Form as RawForm
from wtforms import widgets,TextField,PasswordField, BooleanField,\
     TextAreaField,SubmitField,RadioField,SelectField,SelectMultipleField
from wtforms.ext.sqlalchemy.fields import QuerySelectField
from wtforms.validators import Required, Length,EqualTo,ValidationError,NumberRange#InputRequired
from wtforms.csrf.session import SessionCSRF
from wtforms_alchemy import ModelForm
from app.models import *
import os
import re

class ValidateErrorMixin(object):
    def get_last_error(self):
        for err in self.errors.values():
            return str(err[0])
            
strip_filter = lambda x: x.strip() if x else None
  
class LoginForm(Form,ValidateErrorMixin):#登录
    username   =TextField('用户名',validators=[Required(message='请输入用户名!')])
    password   =PasswordField('密码')
    remember_me=BooleanField('记住我的登录', default = False)
    submit     =SubmitField('登录')

class Users_Form(ModelForm,ValidateErrorMixin):
    class Meta:
        model = Users
        strip_string_fields=True
        field_args = {'username':{'label' : '用户名','validators': [Required(message='用户名不能为空!')]},
                      'remarkname':{'label':'备注名'},
                      'email':{'label' :'Email地址','validators': [Required('Email地址不能为空!')]},
                      'pwd':{'label' :'初始密码','validators': [Required(message='初始密码不能为空!')]}
                      }

    def validate_username(form,field):
        if not re.match('^[a-zA-z][a-zA-Z0-9_]{2,9}$',field.data):
            raise ValidationError('用户名只能是字母,数字和下画线组成!')

    def validate_email(form,field):
        if not re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", field.data):
            raise ValidationError('Email地址无效!')
            
class Config_Form(ModelForm,ValidateErrorMixin):
    class Meta:
        model = Configs
        #strip_string_fields=True
        field_args = {'key'     :{'label' : 'key','validators': [Required(message='KEY不能为空!')]},
                      'value'   :{'label' : 'value'},
                      'descript':{'label' : 'descript'},
                     }

class RepositoryForm(ModelForm,ValidateErrorMixin):
    class Meta:
        model = Repository
        strip_string_fields=True
        field_args = {'name'    :{'label' : '仓库名称','validators': [Required(message='仓库名称不能为空!')]},
                      'remark'  :{'label' : '备注'}
                     }
               
    def validate_name(form,field):
        repos_path=os.path.join(Configs.get_value('SVN_REPOS_PATH'),field.data)
        if not os.path.exists(repos_path):
            raise ValidationError('仓库[%s]不存在!' % repos_path)
            
class ServerForm(ModelForm,ValidateErrorMixin):
    class Meta:
        model = Servers
        strip_string_fields=True
        field_args = {'host'    :{'label' : '主机(host)','validators': [Required(message='主机名不能为空!')]},
                      'port'  :{'label' : '端口','default':'22'},
                      'user':{'label' : '用户名','validators': [Required(message='用户名不能为空!')]},
                      'pwd'  :{'label' : '密码'},
                      'remark'  :{'label' : '备注'}
                     }
               
class DeployForm(Form,ValidateErrorMixin):#部署
    branch        =TextField('分枝(/表示根目录)',validators=[Required(message='请输入分枝名称!')])
    deploy_servers=SelectMultipleField('部署服务器(Ctrl+单击选择或不选)',choices=[])
    deploy_path   =TextField('部署路径(变量 &lt;repos&gt;:仓库名 &lt;branch&gt;:分枝名 )',
                            validators=[Required(message='部署路径不能为空!')])
    init_cmds     =TextAreaField('初始化执行命令')
    cmds          =TextAreaField('每次更新后执行命令')
    
    
